package me.zhangsanfeng.gpss.service.impl;

import me.zhangsanfeng.gpss.common.entity.Sorter;
import me.zhangsanfeng.gpss.common.utils.QueryConditionUtil;
import me.zhangsanfeng.gpss.common.utils.UpdateUtil;
import me.zhangsanfeng.gpss.dao.InOrderRepository;
import me.zhangsanfeng.gpss.entity.InOrder;
import me.zhangsanfeng.gpss.service.InOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
@Transactional
public class InOrderServiceImpl implements InOrderService {

    @Autowired
    private InOrderRepository repository;

    @Override
    public InOrder insert(InOrder inOrder) {
        return repository.save(inOrder);
    }

    @Override
    public List<InOrder> insertBatch(List<InOrder> inOrders) {
        return repository.saveAll(inOrders);
    }

    @Override
    public void delete(InOrder inOrder) {
        repository.delete(inOrder);
    }

    @Override
    public void deleteBatch(List<InOrder> inOrders) {
        repository.deleteAll(inOrders);
    }

    @Override
    public InOrder update(InOrder inOrder) {
        UpdateUtil.copyNullProperties(repository.getOne(inOrder.getId()),inOrder);
        return repository.saveAndFlush(inOrder);
    }

    @Override
    public List<InOrder> updateBatch(List<InOrder> inOrders) {
        for (InOrder inOrder : inOrders) {
            UpdateUtil.copyNullProperties(repository.getOne(inOrder.getId()),inOrder);
        }
        return repository.saveAll(inOrders);
    }

    @Override
    public InOrder selectOne(InOrder inOrder) {
        return repository.findOne(Example.of(inOrder)).get();
    }

    @Override
    public List<InOrder> selectList(InOrder inOrder) {
        /*排序标识*/
        Sorter sorter = inOrder.getSorter();

        Map<String, Object> condition;
        //不排序
        if (null == sorter.getDesc() && null == sorter.getAsc() && null == sorter.getPrior()) {
            condition = QueryConditionUtil.getWhereCondition(inOrder, false, false);
        } else {
            condition = QueryConditionUtil.getWhereCondition(inOrder, false, true);
        }

        return QueryConditionUtil.getQueryInstanceOfList(condition, repository);
    }

    @Override
    public Page<InOrder> selectPage(InOrder inOrder) {
        /*排序标识*/
        Sorter sorter = inOrder.getSorter();

        Map<String, Object> condition;
        if (null == sorter.getDesc() && null == sorter.getAsc() && null == sorter.getPrior()){
            condition = QueryConditionUtil.getWhereCondition(inOrder, true, false);
        }else {
            condition = QueryConditionUtil.getWhereCondition(inOrder, true, true);
        }

        return QueryConditionUtil.getQueryInstanceOfPage(condition,repository);
    }
}
